package integrationtest;


import java.sql.Connection;
import java.sql.SQLException;
import java.util.Stack;

import connectionpool.ConnectionPool;



/**
 * @author amahmood
 *
 */
public class WorkerThread implements Runnable
{

    private  ConnectionPool connectionPool = null;

    private Stack<Connection> myConnection = new Stack<Connection>();

    public WorkerThread(ConnectionPool connectionPool)
    {
        this.connectionPool = connectionPool;
    }

    /**
     * 
     */
    private void getConnection()
    {
        try
        {
            myConnection.push(connectionPool.getConnection());
        }
        catch (SQLException e)
        {
            System.out.println(e);
        }
        System.out.println(Thread.currentThread().getName() + ": Got conneciton");

    }

    /**
     * 
     */
    private void releaseAllConnections()
    {
        while (!myConnection.isEmpty())
        {
            releaseConnection();
        }
        System.out.println(Thread.currentThread().getName() + ": All conneciton released");
    }

    /**
     * 
     */
    private void releaseConnection()
    {
        if (!myConnection.isEmpty())
        {
            try
            {
                connectionPool.releaseConnection(myConnection.pop());
            }
            catch (SQLException e)
            {
                System.out.println(e);
            }
            System.out.println(Thread.currentThread().getName() + ": Conneciton released");

        }
    }

    /*
     * (non-Javadoc)
     * 
     * @see java.lang.Runnable#run()
     */
    public void run()
    {

        try
        {
            for (int i = 0; i < 10; i++)
            {
                if (RandomNumberUtil.nextInt(10) % 2 == 0)
                {
                    getConnection();
                }
                else
                {
                    releaseConnection();
                }

                try
                {
                    Thread.sleep(RandomNumberUtil.nextInt(1000));
                }
                catch (InterruptedException e)
                {
                    System.out.println(e.getMessage() + " " + e);
                }
            }

        }
        catch (Exception e)
        {
            System.out.println(e);
        }

        releaseAllConnections();
    }
}
